package com.imooc.mmall.transactiona;

import com.imooc.mmall.dao.UserMapper;
import com.imooc.mmall.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import java.sql.Timestamp;
import java.util.Date;

/**
 * 代码方式——实现事物
 */
@Service
@Slf4j
public class CustomerServiceTxInCode {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PlatformTransactionManager transactionManager;


    public void create(User user) {
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE);
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        def.setTimeout(15);
        TransactionStatus status = transactionManager.getTransaction(def);
        try {
            createUser(user);
            LocalTranJdbcApplication.createError();
            transactionManager.commit(status);
        } catch (Exception e) {
            transactionManager.rollback(status);
        }
    }

    public void createUser(User user){
        userMapper.insert(user);
    }
}
